package com.rabbiter.oes.util;

import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class FaceRecognition {
    public static final String API_KEY = "yKlo5ylbIX0HgEqrdZZfaO4C";
    public static final String SECRET_KEY = "KPf9lZQ1sIXsqtAsQyObSMMY7ifEjGW6";
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    /**+
     * 查询组
     * @return
     */
    public static String queryGroup(){
        try {
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/getlist?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            return response.body().string();
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 添加组
     * @param gname
     * @return
     */
    public static String addGorup(String gname){
       try {
           MediaType mediaType = MediaType.parse("application/json");
           RequestBody body = RequestBody.create(mediaType, "{\"group_id\":\""+ gname +"\"}");
           Request request = new Request.Builder()
                   .url("https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/add?access_token=" + getAccessToken())
                   .method("POST", body)
                   .addHeader("Content-Type", "application/json")
                   .build();
           Response response = HTTP_CLIENT.newCall(request).execute();
           return response.body().string();
       }catch (Exception e){
           return null;
       }
    }

    /**
     * 删除用户组
     * @param gname
     * @return
     */



    public static String delGroup(String gname){
       try {
           MediaType mediaType = MediaType.parse("application/json");
           RequestBody body = RequestBody.create(mediaType, "{\"group_id\":\""+gname+"\"}");
           Request request = new Request.Builder()
                   .url("https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/delete?access_token=" + getAccessToken())
                   .method("POST", body)
                   .addHeader("Content-Type", "application/json")
                   .build();
           Response response = HTTP_CLIENT.newCall(request).execute();
           return response.body().string();
       }catch (Exception e){
           return null;
       }
    }

    /**
     * 复制用户
     * @param did
     * @param sid
     * @param uid
     * @return
     */

    public static String cloneUser(String did,String sid,String uid){
        try {
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "{\"dst_group_id\":\""+did+"\",\"src_group_id\":\""+sid+"\",\"user_id\":\""+uid+"\"}");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/copy?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            return response.body().string();
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 获取组列表
     * @param gname
     * @return
     */
    public static String getGorupUser(String gname){
        try {
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "{\"group_id\":\""+gname+"\"}");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/getusers?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            return response.body().string();
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 删除用户
     * @param gid
     * @param uid
     * @return
     */

    public static String delUser(String gid,String uid){
        try {
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "{\"group_id\":\""+gid+"\",\"user_id\":\""+uid+"\"}");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/delete?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            return response.body().string();
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 更新用户人脸
     * @param gid
     * @param image
     * @param uid
     * @return
     */

    public static String updateUser(String gid,String image,Integer uid){
        try {
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "{\"group_id\":\""+gid+"\",\"image\":\""+image+"\",\"image_type\":\"BASE64\",\"user_id\":\""+uid+"\"}");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/update?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            return response.body().string();
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 人脸删除
     * @param token
     * @param gid
     * @param uid
     * @return
     */

    public static String delFace(String token,String gid,String uid){
        try {
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "{\"face_token\":\""+token+"\",\"group_id\":\""+gid+"\",\"log_id\":1,\"user_id\":\""+uid+"\"}");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rest/2.0/face/v3/faceset/face/delete?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            return response.body().string();
        }catch (Exception e){
            return null;
        }
    }



    /**
     * 注册人脸
     * @param group_id
     * @param path
     * @param user_id
     * @return
     */
    public static String addFace(String group_id ,   String path , String user_id){
        try {
            MediaType mediaType = MediaType.parse("application/json");    // {"aa" : "aa" , "aaxx" : "xx"}
            // image 可以通过 getFileContentAsBase64("C:\fakepath\2.jpg") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
            String base64 = getFileContentAsBase64(path);
            RequestBody body = RequestBody.create(mediaType, "{\"group_id\":\""+group_id+"\",\"image\":\""+base64+"\",\"image_type\":\"BASE64\",\"user_id\":\""+user_id+"\"}");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            return response.body().string();
        }catch (Exception e){
            System.out.println(e);
            return null;
        }
    }

    //人脸查询
    public static String FaceSearch(String getGroup_id,String getBase64) {
        try {
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "{\"group_id_list\":\""+getGroup_id+"\",\"image\":\""+getBase64+"\",\"image_type\":\"BASE64\"}");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rest/2.0/face/v3/search?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            return response.body().string();
        }catch (Exception e){
            System.out.println(e);
            return null;
        }
    }





    static String getFileContentAsBase64(String path) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(b);
        return base64;
    }



    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }
}
